package org.walker.iotScheduling.modules.iot.v2.factory;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.walker.iotScheduling.modules.iot.task.ScheduledTask;
import org.walker.iotScheduling.modules.iot.v2.strategy.TimeStrategy;
import org.walker.iotScheduling.modules.iot.v2.strategy.impl.FixedRateSchedulingStrategy;

import java.util.*;

/**
 * 使用工厂模式来动态创建任务调度策略,支持灵活增加任务和调度策略
 *
 * @author :zhuangguojin
 * @since :2024/12/4 16:23
 */
@Component
@RequiredArgsConstructor(onConstructor_ = {@Lazy, @Autowired})
public class TimeStrategyFactory {
    //存放成功注册的任务策略
    private final Map<String, TimeStrategy> timeStrategymap = new HashMap<>();
    //获取已定义好的任务策略
    private final Map<String, ScheduledTask> scheduledTaskmap;

    // 动态注册策略
    public void registerStrategy(String strategyName, String cronExpression) {
        ScheduledTask task = scheduledTaskmap.get(strategyName);
        if (task != null) {
            TimeStrategy timeStrategy = new FixedRateSchedulingStrategy(task, cronExpression);
            timeStrategymap.put(strategyName, timeStrategy);
        } else {
            throw new IllegalArgumentException("No task found for strategy: " + strategyName);
        }
    }

    public List<TimeStrategy> getAllStrategies() {
        return new ArrayList<>(timeStrategymap.values());
    }
}
